package com.jstyle.beatecg.activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.jstyle.beatecg.NetWork.NetWorkUtil;
import com.jstyle.beatecg.R;
import com.jstyle.beatecg.base.BaseActivity;
import com.jstyle.beatecg.dao.DbManager;
import com.jstyle.beatecg.daoManager.UserInfoDaoManager;
import com.jstyle.beatecg.model.NetResultData;
import com.jstyle.beatecg.model.UserInfo;
import com.jstyle.beatecg.util.GlobalConast;
import com.jstyle.beatecg.util.ImageUtils;
import com.jstyle.beatecg.util.NetWorkConast;
import com.jstyle.beatecg.util.NetWorkException;
import com.jstyle.beatecg.util.SHA1;
import com.jstyle.beatecg.util.SharePreferenceUtils;
/*import com.jstyle.beatecg.util.ShareTools;*/
import com.jstyle.beatecg.view.EditTextWithDelete;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;


/**
 * 登录
 */
public class LoginActivity extends BaseActivity /*implements ShareTools.ShareListener*/ {
    private static final String TAG = "LoginActivity";

    @BindView(R.id.et_login_phonenumber)
    EditTextWithDelete etLoginPhonenumber;
    @BindView(R.id.et_login_password)
    EditTextWithDelete etLoginPassword;
    @BindView(R.id.tv_login_forgetpassword)
    TextView tvLoginForgetpassword;
    @BindView(R.id.bt_login_login)
    Button btLoginLogin;
    @BindView(R.id.bt_login_signin)
    Button btLoginSignin;
    @BindView(R.id.iv_wechat_login)
    ImageView btWechatLogin;
    @BindView(R.id.iv_qq_login)
    ImageView btQqLogin;
    @BindView(R.id.iv_weibo_login)
    ImageView btWeiboLogin;

   // ShareTools shareTools;
    String token;
    private String countryCode="0086-";
    Observer<NetResultData> observer = new Observer<NetResultData>() {


        @Override
        public void onError(Throwable e) {
            disMissProgressDialog();
            if (e instanceof NetWorkException) {
                String msg = NetWorkConast.getResult(((NetWorkException) e).getMsgCode(), LoginActivity.this);
                showToast(msg);
            }
            Log.i(TAG, "onError: " + e.toString());
        }

        @Override
        public void onComplete() {

        }

        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(NetResultData netResultData) {
            disMissProgressDialog();
            int msgCode = netResultData.getMsgCode();
            String msg = NetWorkConast.getResult(msgCode, LoginActivity.this);
            if (msgCode == NetResultData.Success_Code) {
                //   msg = "登陆成功";
                saveUserInfo(netResultData.getData());
                boolean isFirst = SharePreferenceUtils.getSpBoolean(GlobalConast.KEY_isFirst);
               startActivity(isFirst ? UserInfoSettingActivity.class : MainActivity.class);
                finish();
                return;
            } else if (msgCode == NetResultData.Failed_Code) {
                msg = getResources().getString(R.string.login_loginfailed);
            }
            showToast(msg);
        }
    };

    @BindView(R.id.bt_login_getCountryCode)
    Button btLoginGetCountryCode;
    private String language;

    private void saveUserInfo(String id) {
        UserInfo userInfo = new UserInfo();
        String phone = etLoginPhonenumber.getText().toString();
        String psdS = etLoginPassword.getText().toString();
        String psd = psdS.length() == 32 ? psdS : SHA1.md5Encoder(psdS);
        userInfo.setUserId(Long.valueOf(id));
      //  userInfo.setToken(token);
        userInfo.setPhone(phone);
        userInfo.setUserpwd(psd);
        UserInfoDaoManager.insertUser(userInfo);
        SharePreferenceUtils.setSpBoolean( SharePreferenceUtils.KEY_REMIND_PSD, checkboxLogin.isChecked());
        SharePreferenceUtils.setSpBoolean(SharePreferenceUtils.KEY_LOGIN, true);
      //  if (!checkboxLogin.isChecked()) return;
        SharePreferenceUtils.setSpString(SharePreferenceUtils.KEY_PHONE, phone);
        SharePreferenceUtils.setSpString(SharePreferenceUtils.KEY_PSD, psd);
    }


    @BindView(R.id.checkbox_login)
    CheckBox checkboxLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        SharePreferenceUtils.init(this);
        DbManager.init(this);
        ButterKnife.bind(this);
        showStatusBar();
        initView();
        Locale locale = getResources().getConfiguration().locale;
        language = locale.getLanguage();
        /*shareTools = new ShareTools(this);
        shareTools.setShareListener(this);*/

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void initView() {
        boolean isRemind = SharePreferenceUtils.getSpBoolean(SharePreferenceUtils.KEY_REMIND_PSD);
        if (isRemind) {
            findUserInfo();
            checkboxLogin.setChecked(true);
        }
        checkboxLogin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            }
        });
    }

    private void findUserInfo() {
        String phone = SharePreferenceUtils.getSpString(SharePreferenceUtils.KEY_PHONE);
        String psd = SharePreferenceUtils.getSpString(SharePreferenceUtils.KEY_PSD);
        if (!TextUtils.isEmpty(phone)) etLoginPhonenumber.setText(phone);
        if (!TextUtils.isEmpty(psd)) etLoginPassword.setText(psd);
    }

    @Override
    protected void showStatusBar() {
       // ScreenUtils.setStatusBarColor(llTitle,getResources().getColor(R.color.colorPrimary));
    }

    @OnClick({R.id.bt_login_getCountryCode,R.id.tv_login_forgetpassword, R.id.bt_login_login, R.id.bt_login_signin, R.id.iv_wechat_login, R.id.iv_qq_login, R.id.iv_weibo_login})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_login_forgetpassword:
                startActivity(FindPasswordActivity.class);
                break;
            case R.id.bt_login_login:
                login();
                break;
            case R.id.bt_login_signin:
                startActivity(SignInActivity.class);
                break;
            case R.id.iv_wechat_login:
               // shareTools.wechatLogin();
                break;
            case R.id.iv_qq_login:

                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                      // shareTools.qqLogin();
                    }
                }.start();
                break;
            case R.id.iv_weibo_login:
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        //shareTools.sinaLogin();
                    }
                }.start();

                break;
            case R.id.bt_login_getCountryCode:
                getCountryCode();
                break;
        }
    }
    private void getCountryCode() {
   /*     phone.showForResult(this, (Intent) null, new FakeActivity() {
            @Override
            public void onResult(HashMap<String, Object> data) {
                super.onResult(data);
                String currentId = (String) data.get("id");
                String[] res = SMSSDK.getCountry(currentId);
                btLoginGetCountryCode.setText("+" + res[1]);
                countryCode="00"+res[1]+"-";
            }
        });*/
    }
    private void login() {
        if(!NetWorkUtil.isNetworkConnected(this)){
            showToast(getString(R.string.Network_not_availa));
            return;
        }
        String account = etLoginPhonenumber.getText().toString();
        String password = etLoginPassword.getText().toString();
        if (TextUtils.isEmpty(password) || TextUtils.isEmpty(account)) {
            showToast(getString(R.string.login_input_all));
            return;
        }
        Map<String, Object> map = new HashMap<>();
        if(language.equals("zh")){
            map.put(NetWorkConast.KEY_PHONE,countryCode+account);
        }else{
            map.put(NetWorkConast.KEY_userEmail,account);
        }
        map.put(NetWorkConast.KEY_userpwd, password.length() == 32 ? password : SHA1.md5Encoder(password));
        NetWorkUtil.addSHA1(map);
        NetWorkUtil.getInstance().getJstyleApi().
                login(map).subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
                                                          @Override
                                                          public void accept(Disposable disposable) throws Exception {
                                                              showProgressDialog(getString(R.string.login_logining));
                                                          }
                                                      }

        ).observeOn(AndroidSchedulers.mainThread()).subscribe(observer);
    }

 /*   @Override
    public void ShareSuccess(String userName, String headUrl, String platName, String userId) {

        getAuthUserInfo(headUrl,platName,userId);
        SharePreferenceUtils.setSpString(SharePreferenceUtils.KEY_NICKNAME,userName);

    }*/

    private void saveUserIcon(String headUrl) {
        NetWorkUtil.getInstance().getJstyleApi().downloadIcon(headUrl).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        
                    }

                    @Override
                    public void onNext(ResponseBody value) {

                        try {
                            writeToDisk(value);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i(TAG, "onError: "+e.getMessage());
                    }

                    @Override
                    public void onComplete() {


                    }
                });
    }
    private void writeToDisk(ResponseBody responseBody) throws IOException {
        File file = new File(ImageUtils.headPath);
        File fileIcon = new File(ImageUtils.headPath +ImageUtils.md5Encoder(NetWorkUtil.getToken()));
        Log.i(TAG, "writeToDisk: "+ImageUtils.md5Encoder(NetWorkUtil.getToken()));
        if (!file.exists()) {
            file.mkdirs();
        }
        if (fileIcon.exists()&&fileIcon.length()==responseBody.contentLength()) {
            finishLogin();
            return;
        }
        byte[] buffer = new byte[1024*8];
        int len;
        FileOutputStream out = new FileOutputStream(fileIcon);
        InputStream in=responseBody.byteStream();
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        out.flush();
        out.close();
        in.close();
        finishLogin();
    }
    void finishLogin(){
//        boolean isFirst = SharePreferenceUtils.getSpBoolean( GlobalConast.KEY_isFirst);
//        startActivity(isFirst ? UserInfoSettingActivity.class : MainActivity.class);
//        finish();
    }

    private void getAuthUserInfo(final String url, String platName, String userId) {
        Map<String,Object> maps=new HashMap<>();
        maps.put(NetWorkConast.KEY_oauthName,platName);
        maps.put(NetWorkConast.KEY_openID,userId);
        NetWorkUtil.getInstance().getJstyleApi().loginAuth(maps)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NetResultData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NetResultData value) {
                        int code=value.getMsgCode();
                        if(code==NetResultData.Success_Code){
                            SharePreferenceUtils.setSpString(SharePreferenceUtils.KEY_AUTH_USERID, value.getData());
                            SharePreferenceUtils.setSpBoolean(SharePreferenceUtils.KEY_LOGIN, true);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        saveUserIcon(url);
                    }
                });
    }

 /*   @Override
    public void ShareFailed() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showToast(getString(R.string.login_loginfailed));
            }
        });
    }

    @Override
    public void shareCancel() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showToast(getString(R.string.login_third_usercancel));
            }
        });
    }*/


}
